<?php

class Cat_Crawler_Std extends Cat_Crawler_Base
{		
	function __construct()
	{
		$this->setParam( 'input.extension', '.stub.php' );
		$this->setParam( 'output.extension', '.php' );
		$this->setParam( 'input.path', LIB_BASE_DIR );
		$this->setParam( 'output.path', LIB_BASE_DIR );
	}
		
	function crawl()
	{
		$this->processFiles( $this->targets );
	}

	function processFile( $file )
	{		
		$out = @file_get_contents( $file );
		
		if ( $out !== false )
		{			
			$outfile = $this->convertInputToOutputFileName( $file );
			
			$this->setParam( 'input.filename', $file );
			$this->setParam( 'output.filename', $outfile );
			$this->setParam( 'input.path', $this->getParam( 'input.path' ) );
			$this->setParam( 'output.path', $this->getParam( 'output.path' ) );
			
			$out = $this->processString( $out );			
			file_put_contents( $outfile, $out );
		}
		else
		{
			throw new Cat_Exception( Cat_Exception_Messages::NO_FILE );
		}
		
	}
	
	function processFiles( $files = null )
	{
		if ( $files == null )
		{
			$files = $this->getFiles();
		}
		
		foreach( $files as $file )
		{			
			try
			{
    			$this->processFile( $file );
			}
			catch( Exception $e )
			{
				echo $e->getMessage();
			}
		}
	}	

	function processString( $string )
	{	
		foreach( $this->getProcessors() as $p )
		{		
		    $this->cloneParams( $p );
			$string = $p->processString( $string ); 
		}

		return $string;
	}
	
	function getFiles( $path = null )
	{
		if ( $path == null )
		{
			$path = $this->getParam( 'input.path' );
		}
		
		$glob = glob( $path . '/*' );
		
		$files = array();
		
		foreach( $glob as $file )
		{
			if ( is_dir( $file ) )
			{
				$files = array_merge( $files, $this->getFiles( $file . '/*' ) );
			}
			else
			{
				if ( Cat_Strings :: endsWith( $file, $this->getParam( 'input.extension' ) ) )
				{
					$files[ $file ] = $file;
				}
			}
		}
		
		return $files;
	}
	
	private function convertToRelativeFileNameWithoutExtension( $file )
	{
		return mb_substr( $this->convertToRelativeFileName( $file ), 0, -1 * mb_strlen( $this->getParam( 'input.extension' ) ) );
	}
	
	private function convertToRelativeFileName( $file )
	{
		return trim( trim( mb_substr( realpath( $file ), mb_strlen( realpath( $this->getParam( 'input.path' ) ) ) ), '/' ), '\\' );		
	}
	
	private function convertInputToOutputFileName( $file )
	{
		$outpath = $this->getParam( 'output.path' );
		$file = $outpath . '/' . $this->convertToRelativeFileNameWithoutExtension( $file ) . $this->getParam( 'output.extension' );
		Cat_Files::touch( $file );
		return $file;
	}
}

?>
